package netty.w3cschool.echo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

public class EchoServer {
    private final int port;

    public EchoServer(int port) {
        this.port = port;
    }

    public static void main(String[] args) throws Exception{
        if (args.length !=1){
            System.err.println("Usage: "+EchoServer.class.getSimpleName()+"<port>");
            return;
        }
        int port = Integer.parseInt(args[0]); //设置端口值
        new EchoServer(port).start();   // 呼叫服务器的start方法

    }

    public void start() throws Exception{
        NioEventLoopGroup group = new NioEventLoopGroup(); //创建EventLoopGroup

        try{
            ServerBootstrap b = new ServerBootstrap(); // 创建ServerBootstrap
            b.group(group)
                    .channel(NioServerSocketChannel.class) //指定使用Nio传输Channel
                    .localAddress(new InetSocketAddress(port)) //设置socket地址使用所选的端口
                    .childHandler(new ChannelInitializer<SocketChannel>() { //添加EchoServerHandler 到 Channel 的ChannelPipeline
                        @Override
                        protected void initChannel(SocketChannel channel) throws Exception {
                            channel.pipeline().addLast(new EchoServerHandler());
                        }
                    });
            ChannelFuture f = b.bind().sync();            //绑定的服务器;sync等待服务器关闭
            System.out.println(EchoServer.class.getName() + " started and listen on " + f.channel().localAddress());
            f.channel().closeFuture().sync();            //关闭 channel 和 块，直到它被关闭
        }finally {
            group.shutdownGracefully(); //关机的 EventLoopGroup，释放所有资源。
        }

    }

}
